import {Observer, loading, closeLoading, generateGuid, getTencentIfrSrc} from './util'
import {Message} from 'element-ui'
import store from '../personal/store/index'
import eRes from './editorRes'
import axios from 'axios'

window.Observer = Observer;
window.loading = loading;
window.closeLoading = closeLoading;
window.generateUUID = generateGuid;
window.resourceHandler = eRes;
window.tencentVideoTypes = ['.wmv', '.wm', '.asf', '.asx', '.rm', '.rmvb', '.ra', '.ram',
    '.mpg', '.mpeg', '.mpe', '.vob', '.dat', '.mov', '.3gp', '.mp4', '.mp4v',
    '.m4v', '.mkv', '.avi', '.flv', '.f4v']; // 腾讯云视频上传支持的格式
window.bootbox = {
    succ(message) {
        Message({
            message: message,
            type: 'success'
        });
    },
    warn(message) {
        Message({
            message: message,
            type: 'warning'
        });
    },
    fail(message) {
        Message({
            message: message,
            type: 'error'
        });
    },
    dialog() {
        return {
            init(fn) {
                loading();
                fn();
            },
            modal() {
                closeLoading();
            }
        }
    }
};
// 腾讯云上传获取签名
window.tencentGetSig = function (callback) {
    let url = "";
    if (window.location.hostname == "localhost") {
        url = 'http://192.168.107.77/EN/api/Tencent/GetTencentSign'; // 调试模式
    } else {
        let prefix = (window.location.origin || (window.location.protocol + "//" + window.location.host))
        url = prefix + '/EN/api/Tencent/GetTencentSign'; // 上线
    }
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        success: function (res) {
            if (res && res.Code === 200) {
                callback(res.Data);
            } else {
                console.log(res);
                return Message({
                    showClose: true,
                    message: "获取签名失败",
                    type: "error",
                    duration: 2000
                });
            }
        },
        error: function (err) {
            console.log(err);
            return Message({
                showClose: true,
                message: "获取签名失败",
                type: "error",
                duration: 2000
            });
        }
    });
}
/**
 * 新版的腾讯云获取签名
 */
window.tencentGetSigAxios = function () {
    let url = "";
    if (window.location.hostname == "localhost") {
        url = 'http://192.168.107.77/EN/api/Tencent/GetTencentSign'; // 调试模式
    } else {
        let prefix = (window.location.origin || (window.location.protocol + "//" + window.location.host))
        url = prefix + '/EN/api/Tencent/GetTencentSign'; // 上线
    }
    return axios.post(url).then(res => {
        if(res && res.status === 200 && res.data.Code === 200){
            return res.data.Data;
        }else{
            return Message({
                showClose: true,
                message: "获取签名失败",
                type: "error",
                duration: 2000
            });
        }
    }).catch(err => {
        return Message({
            showClose: true,
            message: "获取签名失败",
            type: "error",
            duration: 2000
        });
    });
}
/**
 * 腾讯云视频的上传方法
 * @param file 视频对象
 * @param addedName 用户输入的视频名称
 */
window.tencentUploadVideo = function (file, addedName) {
    loading();
    let strSize = getProperSize(file.size);
    var resultMsg = qcVideo.ugcUploader.start({
        videoFile: file,
        getSignature: tencentGetSig,
        success: function (result) {
        },
        error: function (result) {
            console.log(result);
            closeLoading();
            bootbox.fail(result.msg + '上传失败');
        },
        progress: function (result) {
            closeLoading();
            let obj = store.state.objTencentUp;
            obj[result.taskId] = {
                videoName: result.name,
                videoSize: file.size,
                videoSizeStr: strSize,
                percentage: Math.floor(result.curr * 100) + '%',
                curr: result.curr
            }
            store.commit('setTencentUp', obj);
        },
        finish: function (result) {
            // console.log(result);
            eRes.addResource({
                type: 'video',
                ifrSrc: getTencentIfrSrc(result.fileId),
                name: addedName,
                resourceID: result.fileId
            });
            window.addToDB(result, file.size);
            bootbox.succ('视频上传成功!');
        }
    });
    if (resultMsg) {
        bootbox.fail(resultMsg);
    }
}
window.addToDB = function (res, fileSize) {
    let moduleCode = window.moduleCode
      , resourceCode = window.resourceID;
    if(!window.typeId){
        // 课题项目
        moduleCode = window.moduleCode;
        resourceCode = window.rcForKT;
    }
    axios
        .post(
            "/api/Resouce/SaveTencentVideo",
            qs.stringify({
                coverName: res.coverName || '',
                coverUrl: res.coverUrl || '',
                fileId: res.fileId || '',
                videoName: res.videoName || '',
                videoUrl: res.videoUrl || '',
                moduleCode: moduleCode,
                resourceCode: resourceCode,
                courseCode: '',
                resourceType: '',
                isAddResource: false,
                fileSize: fileSize
            })
        )
        .then(res => {
            // console.log(res);
            if (res && res.data && res.data.Code === 200) {
                return;
            }
            bootbox.fail("添加资源失败");
        })
        .catch(err => {
            console.log(err);
            bootbox.fail("添加资源失败");
        });
}
/**
 * 计算合适的文件大小
 * @param size
 */
window.getProperSize = function (size) {
    let kilobytes = size / 1024;
    if (kilobytes < 1024) {
        return Math.floor(kilobytes) + 'KB';
    }
    let megabytes = kilobytes / 1024;
    if (megabytes < 1024) {
        return megabytes.toFixed(1) + 'MB';
    }
    let gigabytes = megabytes / 1024;
    if (gigabytes < 1024) {
        return gigabytes.toFixed(1) + 'GB';
    }
}
